package com.project.base.baseproject.AppCustoms.Tool;

import android.app.ActivityManager;
import android.content.Intent;
import android.os.Environment;

import com.project.base.baseproject.AppCustoms.MyApplication.MyApplication;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.content.Context.ACTIVITY_SERVICE;

/**
 * Created by mac on 2017/6/19.
 */
//异常收集 程序中未使用try catch发生异常会走此方法
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //上传服务器
        //写入文件
        long timeMillis = System.currentTimeMillis();
        Date date = new Date(timeMillis);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String formatTime = sdf.format(date);
        File crashFileDir = new File(Environment.getExternalStorageDirectory() + "/BaseProject/Crash");
        if (!crashFileDir.exists()) {
            crashFileDir.mkdirs();
        }
        File crashFile = new File(crashFileDir.getAbsoluteFile() +"/"+ formatTime + ".log");
        try {
            crashFile.createNewFile();
            FileOutputStream e = new FileOutputStream(crashFile);
            PrintStream printStream = new PrintStream(e);
            ex.printStackTrace(printStream);
            printStream.close();
        } catch (FileNotFoundException var12) {
            var12.printStackTrace();
        } catch (IOException var13) {
            var13.printStackTrace();
        } catch (SecurityException var14) {
            var14.printStackTrace();
        }
        //杀死自己的进程 以确保下次启动重新初始化应用
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
        ActivityManager manager = (ActivityManager) MyApplication.getInstance().getSystemService(ACTIVITY_SERVICE);
        manager.killBackgroundProcesses(MyApplication.getInstance().getPackageName());
    }
}
